#!/usr/bin/perl

use strict;
use warnings;
use Finance::Quote;
use Finance::Quote::Yahoo::Europe;
use Finance::QuoteHist;
use Finance::TA;
use DBI;
use Data::Dumper;
use Date::Manip;
use Date::Format;

my $DBCon = DBI->connect("DBI:mysql:database=PFinance;host=localhost", "PFinance", "");
my $sth = $DBCon->prepare("insert into prices values ( ?, ?, ?, ?, ?, ? ) 
                           on duplicate key update open=?, high=?, low=?, close=?");
my @lt = localtime(time);
my $rem = $DBCon->prepare("DELETE FROM prices WHERE datediff('".strftime("%Y-%m-%d",@lt).
                          "',date)>600 AND Stock=?");

open (my $sf, "<", "100_list") or die "Can't open 100 file";
while (<$sf>){
    chomp;
    getAndStorePrices($_,100);
}

sub getAndStorePrices {
    my $stock = shift;
    my $mult = shift;
    my $hq = Finance::QuoteHist->new ( symbols => [ $stock ],
                                       start_date => '500 business days ago',
                                       end_date => 'today');
    for my $row ($hq->quotes()){
        my ($symbol, $date, $open, $high, $low, $close, $volume) = @$row;
        my @vals = ( $symbol , $date , $open , $high , $low , $close , $open , $high , $low , $close );
        print "Got values @vals\n";
        $sth->execute(@vals) || warn "Failed to insert: $!\n";
    }
    
    my $q = Finance::Quote->new;
    $q->timeout(60);
    my %quotes = $q->fetch("yahoo", $stock);
    $rem->execute($stock);
    my @vals = ($stock);
    $quotes{$stock , 'date'} = UnixDate( ParseDate($quotes{$stock , 'date'}), '%Y-%m-%d' );
    for my $label (qw(open high low last)){
        $quotes{$stock , $label} *= $mult;
    }
    for my $label (qw(date open high low last open high low last)){
        push @vals, $quotes{$stock , $label};
    }
    print "Got values @vals\n";
    $sth->execute(@vals) || warn "Failed to insert: $!\n";
}
